package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@Service(version = "1.0.0", interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;

    @Override
    public Result findPAge(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<CheckGroup> checkGroupPage = checkGroupDao.findByCondition(queryPageBean.getQueryString());
        PageResult pageResult = new PageResult();
        pageResult.setRows(checkGroupPage.getResult());
        pageResult.setTotal(checkGroupPage.getTotal());
        return Result.success(pageResult);
    }

    @Override
    public List<CheckItem> findAll() {
        return checkGroupDao.findAll();
    }

    @Override
    public Result add(CheckGroup checkGroup) {
        checkGroupDao.add(checkGroup);
        List<Integer> checkitemIds = checkGroup.getCheckitemIds();
        for (Integer checkitemId : checkitemIds) {
            checkGroupDao.addCheckGroupAndCheckItem(checkGroup.getId(), checkitemId);
        }
        return Result.success(null);
    }

    @Override
    public Result findById(Integer id) {
        CheckGroup checkGroup = checkGroupDao.findById(id);
        List<CheckItem> checkItemList = checkGroupDao.findAll();
        List<Integer> checkItemIds = checkGroupDao.findCheckGroupAndCheckItem(id);
        final HashMap<String, Object> map = new HashMap<>();
        map.put("fromData", checkGroup);
        map.put("tableData", checkItemList);
        map.put("checkitemIds", checkItemIds);
        return Result.success(map);
    }

    @Override
    public Result update(CheckGroup checkGroup) {
        checkGroupDao.update(checkGroup);
        checkGroupDao.deleteCheckGroupAndCheckItem(checkGroup.getId());
        List<Integer> checkitemIds = checkGroup.getCheckitemIds();
        for (Integer checkitemId : checkitemIds) {
            checkGroupDao.addCheckGroupAndCheckItem(checkGroup.getId(), checkitemId);
        }
        return Result.success(null);
    }

    @Override
    public Result delete(Integer id) {
        checkGroupDao.delete(id);
        return Result.success(null);
    }
}
